//
//  BadgeButton.swift
//  微博项目
//
//  Created by admin on 16/3/3.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class BadgeButton: UIButton {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    var badge:Int = 0
        {
            didSet{
                self.layoutSubviews()
            }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        let badgeImage = UIImage(imageLiteral: "main_badge")
        self.setBackgroundImage(badgeImage.stretchableImageWithLeftCapWidth(5, topCapHeight: 5), forState: UIControlState.Normal)
        self.titleLabel?.font = self.titleLabel?.font.fontWithSize(11)
        self.adjustsImageWhenHighlighted = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        if badge <= 0
        {
            self.frame = CGRect.zero
//            self.enabled = false
            return
        }
//        self.enabled = true
        let badgeNumber:NSString = "\(badge)"
        let badgeNumberSize = badgeNumber.sizeWithAttributes([NSFontAttributeName : (self.titleLabel?.font)!])
        let badgeImage = UIImage(imageLiteral: "main_badge")
        if badgeNumberSize.width > badgeImage.size.width
        {
            self.bounds = CGRectMake(0, 0, badgeNumberSize.width, badgeImage.size.height)
        }
        else
        {
            self.bounds = CGRectMake(0, 0, badgeImage.size.width, badgeImage.size.height)
        }
        self.setTitle(badgeNumber as String, forState: UIControlState.Normal)
    }

}
